package com.yuke.cloud.service.smc.controller.frontend;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.DateUtil;
import com.yuke.cloud.common.util.PublicUtil;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.cmc.dto.CmsSysInfoDto;
import com.yuke.cloud.service.api.cmc.service.CmcFeignApi;
import com.yuke.cloud.service.api.omc.dto.OdsOrderDto;
import com.yuke.cloud.service.api.omc.service.OmcOrderFeignApi;
import com.yuke.cloud.service.api.uac.dto.AccEmployeeInfoDto;
import com.yuke.cloud.service.api.uac.dto.UserInfoDto;
import com.yuke.cloud.service.api.uac.service.UacUserFeignApi;
import com.yuke.cloud.service.smc.dto.DmsSendDto;
import com.yuke.cloud.service.smc.dto.DmsStoreDto;
import com.yuke.cloud.service.smc.entity.DmsSend;
import com.yuke.cloud.service.smc.entity.DmsStore;
import com.yuke.cloud.service.smc.service.DmsSendService;
import com.yuke.cloud.service.smc.service.DmsStoreService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.yuke.cloud.common.util.DateUtil.monthTimeBegin;
import static com.yuke.cloud.common.util.DateUtil.monthTimeEnd;

/**
* Created by zn on 2020/07/16.
*/
@Api(value = "WEB - DmsSendController", tags = "处理DmsSend相关请求", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
@RequestMapping("/dms/send")
public class DmsSendController extends BaseController {
    @Resource
    private DmsSendService dmsSendService;
    @Resource
    private DmsStoreService dmsStoreService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Resource
    private OmcOrderFeignApi omcOrderFeignApi;
    @Resource
    private UacUserFeignApi uacUserFeignApi;
    @Resource
    private CmcFeignApi cmcFeignApi;


    @PostMapping
    @ApiOperation(httpMethod = "POST", value = "新增一条记录")
    public Wrapper add(@ApiParam(name = "dmsSend", value = "该数据记录的POJO") @RequestBody DmsSend dmsSend) {
        dmsSendService.save(dmsSend);
        return WrapMapper.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除一条记录")
    public Wrapper delete(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        dmsSendService.deleteById(id);
        return WrapMapper.ok();
    }

    @PutMapping
    @ApiOperation(httpMethod = "PUT", value = "修改一条记录")
    public Wrapper update(@ApiParam(name = "dmsSend", value = "需要修改的内容") @RequestBody DmsSend dmsSend) {
        dmsSendService.update(dmsSend);
        return WrapMapper.ok();
    }

    @GetMapping("/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据ID获取具体信息")
    public Wrapper<DmsSend> detail(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        DmsSend dmsSend = dmsSendService.findById(id);
        return WrapMapper.ok(dmsSend);
    }

    @GetMapping
    @ApiOperation(httpMethod = "GET", value = "分页获取所有记录")
    public Wrapper<PageInfo<DmsSend>> list(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                           @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<DmsSend> list = dmsSendService.findAll();
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }


    /**
     * 领取派送任务1个
     * @param sendId
     * @return
     */
    @GetMapping("/getSendJob")
    @ApiOperation(httpMethod = "GET", value = "分页获取所有记录")
    public Wrapper<Integer> getSendJob(@RequestParam(defaultValue = "0") Long  sendId,@RequestParam(defaultValue = "0") Long  userId) {
        if (sendId == null || sendId < 1 ){
            return WrapMapper.error("sendId参数错误！");
        }
        if (userId == null || userId < 1 ){
            return WrapMapper.error("userId参数错误！");
        }
        DmsSend dmsSend = new DmsSend();
        dmsSend.setSendId(sendId);
        dmsSend.setUserId(userId);
        dmsSend.setSendStatus((byte)1);
        dmsSend.setUpdateTime(new Date());

        Integer flag = dmsSendService.update(dmsSend);
        return WrapMapper.ok(flag);
    }

    /**
     * 批量领取任务,领取状态0，scopeId
     * @param dmsSend
     * @return
     */
    @PostMapping("/getBatchSendJob")
    @ApiOperation(httpMethod = "POST", value = "批量领取任务")
    public Wrapper<Integer> getBatchSendJob(@RequestBody DmsSend dmsSend) {
        if (dmsSend == null || dmsSend.getUserId() == null || dmsSend.getScopeId() == null ){
            return WrapMapper.error("参数错误！");
        }

        //查找send数据,满足scopeId且状态为0的
        List<DmsSend> dmsSends = dmsSendService.selectSendByScope(dmsSend);
        System.out.println("司机{}获取代发货订单长度为{}"+dmsSends.size());
        logger.info("司机{}获取代发货订单长度为{}",dmsSend.getUserId(),dmsSends.size());
        Integer num = 0;
        if (dmsSends != null && dmsSends.size()>0){
            for (DmsSend item : dmsSends){

                Wrapper<Integer> wrapper = getSendJob(item.getSendId(),dmsSend.getUserId());
                if (wrapper.getCode() == 200){
                    num += wrapper.getResult();
                }
            }
        }

        return WrapMapper.ok(num);
    }
    /**
     * 数据条件查询：userId，payType，sendStatus，sendType，scopeId
     * 司机获取今日任务参数{scopeId:X,sendStatus:0}，scopeId为当前司机的scopeId
     * 统计今日任务数，已完成任务数，待完成任务数。 今日任务数包含scope_id对应订单，和领取的临时任务
     * @param dmsSend
     * @return
     */
    @PostMapping("/selectCount")
    @ApiOperation(httpMethod = "POST", value = "分页获取所有记录")
    public Wrapper<Map> selectCount(@ApiParam(name = "dmsSend", value = "", defaultValue = "0")@RequestBody DmsSend dmsSend) {
        Map map = new HashMap();
        if (dmsSend == null || dmsSend.getUserId() == null  ){
            return WrapMapper.error("参数错误！");
        }
        //今日全部任务
        Example example = new Example(DmsSend.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", dmsSend.getUserId());
        criteria.andCondition("(update_time>='"+DateUtil.getStringDate(DateUtil.todayTimeBegin())+"' or send_status < 3)");
        Integer todayCount = dmsSendService.selectCountByExample(example);
        map.put("todayCount",todayCount);

        //今日已完成的任务
        Example example1 = new Example(DmsSend.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("userId", dmsSend.getUserId());
        criteria1.andEqualTo("sendStatus", 3);
        criteria1.andGreaterThan("updateTime",DateUtil.todayTimeBegin());
        Integer todaySend = dmsSendService.selectCountByExample(example1);
        map.put("todaySend",todaySend);

        //今日剩余需要完成数
        map.put("todayNeed",todayCount-todaySend);
        return WrapMapper.ok(map);
    }


    /**
     * 后台分页请求数据条件查询：userId，payType，sendStatus，sendType，scopeId
     * 司机获取今日任务参数{userId:X},时间为今天0点开始的
     * 司机装车任务{userId:X,sendStatus:2}
     * @param page
     * @param size
     * @param dmsSendDto
     * @return
     */
    @PostMapping("/selectSendList")
    @ApiOperation(httpMethod = "POST", value = "分页获取所有记录")
    public Wrapper<PageInfo<DmsSendDto>> list(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                              @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "1000") Integer size,
                                              @RequestBody DmsSendDto dmsSendDto) {
        System.out.println("分页获取所有记录" + dmsSendDto);
        PageHelper.startPage(page, size);
        if (dmsSendDto.getBeginTime() == null && dmsSendDto.getEndTime() == null ){
            dmsSendDto.setBeginTime(DateUtil.todayTimeBegin());
            dmsSendDto.setEndTime(new Date());
        }
        List<DmsSendDto> list = dmsSendService.selectSendByCondition(dmsSendDto);
        PageInfo pageInfo = new PageInfo(list);
        pageInfo.setList(getSendListInfo(list));
        return WrapMapper.ok(pageInfo);
    }

    private List<DmsSendDto> getSendListInfo(List<DmsSendDto> list){

        List<Long> orderIds = list.stream().map(DmsSendDto::getOrderId).collect(Collectors.toList());
        System.out.println("orderIds="+orderIds);
        if (orderIds == null || orderIds.size() < 1){
            return list;
        }
        List<OdsOrderDto> odsOrderDtoList = omcOrderFeignApi.getbyidS(orderIds);
        System.out.println("getSendListInfo获取的订单"+ odsOrderDtoList);
        if (PublicUtil.isEmpty(odsOrderDtoList)){
            System.out.println("getSendListInfo获取的订单为空");
            return list;
        }
        List<Long> shopIds = odsOrderDtoList.stream().map(OdsOrderDto::getShopId).distinct().collect(Collectors.toList());
        if (shopIds == null || shopIds.size() < 1){
            System.out.println("getSendListInfo获取的订单查找的shopId为空");
            return list;
        }
        List<DmsStoreDto> dmsStoreList = dmsStoreService.selectStoreByShopIds(shopIds);
        System.out.println(dmsStoreList);
        for(DmsSendDto dmsSendDto : list) {
            for (OdsOrderDto odsOrderDto : odsOrderDtoList) {
                if (dmsSendDto.getOrderId().equals(odsOrderDto.getOrderId())) {
                    dmsSendDto.setOdsOrderDto(odsOrderDto);
                    dmsSendDto.setShopId(odsOrderDto.getShopId());
                }
            }
            if (dmsSendDto.getScopeId().equals(0)){
                dmsSendDto.setScopeName("未填写");
            }
            if (dmsSendDto.getShopId() == null){
                continue;
            }
            for (DmsStoreDto dmsStoreDto : dmsStoreList){
                if (dmsSendDto.getShopId().equals(dmsStoreDto.getShopId())){
                    dmsSendDto.setDmsStoreDto(dmsStoreDto);
                }
            }

        }
        return list;
    }

    /**
     * 司机获取今日临时任务接口
     * 参数：{userId:X,scopeId:X,sendStatus:0},获取所有任务派送状态sendStatus为0，且scopeId和司机scopeId不同
     * @param page
     * @param size
     * @param dmsSendDto
     * @return
     */
    @PostMapping("/selectOtherList")
    @ApiOperation(httpMethod = "POST", value = "分页获取所有记录")
    public Wrapper<PageInfo<DmsSendDto>> queryList(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                              @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "1000") Integer size,
                                              @RequestBody DmsSendDto dmsSendDto) {

        PageHelper.startPage(page, size);
        List<DmsSendDto> list = dmsSendService.selectOtherList(dmsSendDto);
        PageInfo pageInfo = new PageInfo(list);
        pageInfo.setList(getSendListInfo(list));
        return WrapMapper.ok(pageInfo);
    }

    /**后台打印订单时，产生送货任务，调用此接口
     * 当只有订单Id时，需要查询店铺scopeId，然后添加到数据库
     * @param dmsSendDto
     * @return
     */
    @PostMapping("/addSend")
    @ApiOperation(httpMethod = "POST", value = "新增一条记录")
    public Wrapper addSend(@ApiParam(name = "dmsSendDto", value = "该数据记录的POJO") @RequestBody DmsSendDto dmsSendDto) {
        if (dmsSendDto == null || dmsSendDto.getOrderId() == null || dmsSendDto.getShopId() == null) {
            return WrapMapper.error("传入参数错误！");
        }
        DmsSend dmsSend = new DmsSend();
        dmsSend.setOrderId(dmsSendDto.getOrderId());
        Integer num = dmsSendService.selectCount(dmsSend);
        //判断是否已经添加过
        if (num > 0){
            return WrapMapper.error("该订单已经列入派送表！");
        }

        Long shopId = dmsSendDto.getShopId();

        DmsStore dmsStore = new DmsStore();
        dmsStore.setShopId(shopId);
        List<DmsStore> dmsStoreList = dmsStoreService.select(dmsStore);

        if (dmsStoreList != null && dmsStoreList.size() > 0){
            dmsSendDto.setScopeId(dmsStoreList.get(0).getScopeId());
        }else{
            dmsSendDto.setScopeId(0);
        }


        dmsSend.setShopId(dmsSendDto.getShopId());
        dmsSend.setScopeId(dmsSendDto.getScopeId());
        dmsSend.setAmountPay(dmsSendDto.getAmountPay());
        dmsSend.setUserId(dmsSendDto.getUserId());
        dmsSend.setSendType((byte)1);
        dmsSend.setSendStatus((byte)0);
        dmsSend.setPayType((byte)0);
        dmsSend.setCreateTime(new Date());
        dmsSendService.save(dmsSend);

        return WrapMapper.ok();
    }
    /**
     * 转单功能
     * @param dmsSend
     * @return
     */
    @PostMapping("/tranSendJob")
    @ApiOperation(httpMethod = "GET", value = "分页获取所有记录")
    public Wrapper<Integer> tranSendJob(@ApiParam(name = "dmsSend", value = "该数据记录的POJO") @RequestBody DmsSend dmsSend) {
        if (dmsSend == null || dmsSend.getSendId() == null || dmsSend.getUserId() == null) {
            return WrapMapper.error("传入参数错误！");
        }

        dmsSend.setSendStatus((byte)4);
        Integer flag = dmsSendService.update(dmsSend);

        //保存redis定时任务，需要时再做,这个任务无人领取，1个小时后还是自己的，统计订单未送达或准时率或许有用
        String id = "SendJob:" +dmsSend.getSendId();
        redisTemplate.opsForValue().set(id, dmsSend, 1, TimeUnit.HOURS);
        return WrapMapper.ok(flag);
    }

    /**
     * 装车发货
     * @param sendId
     * @return
     */
    @GetMapping("/doSendJob")
    @ApiOperation(httpMethod = "GET", value = "分页获取所有记录")
    public Wrapper<Integer> doSendJob(@RequestParam(defaultValue = "0") Long  sendId) {
        if (sendId == null && sendId < 1 ){
            return WrapMapper.error("sendId参数错误！");
        }

        DmsSend dmsSend = new DmsSend();
        dmsSend.setSendId(sendId);
        dmsSend.setSendStatus((byte)2);
        dmsSend.setUpdateTime(new Date());
        Integer flag = dmsSendService.update(dmsSend);
        return WrapMapper.ok(flag);
    }

    /**
     * 确认送达
     * @param sendId
     * @return
     */
    @GetMapping("/endSendJob")
    @ApiOperation(httpMethod = "GET", value = "分页获取所有记录")
    public Wrapper<Integer> endSendJob(@RequestParam(defaultValue = "0") Long  sendId) {
        if (sendId == null && sendId < 1 ){
            return WrapMapper.error("sendId参数错误！");
        }

        DmsSend dmsSend = new DmsSend();
        dmsSend.setSendId(sendId);
        dmsSend.setSendStatus((byte)3);
        dmsSend.setSendTime(new Date());
        dmsSend.setUpdateTime(new Date());
        Integer flag = dmsSendService.update(dmsSend);

        // 更新订单信息
        dmsSend = dmsSendService.findById(sendId);
        OdsOrderDto odsOrderDto = new OdsOrderDto();
        odsOrderDto.setOrderId(dmsSend.getOrderId());
        odsOrderDto.setOrderStatus((byte)2);
        odsOrderDto.setAcceptTime(new Date());
        odsOrderDto.setShippingStatus((byte)3);
        omcOrderFeignApi.updateOrderPay(odsOrderDto);

        return WrapMapper.ok(flag);
    }

    /**
     * 司机装车发货的订单详情列表
     *
     * @param dmsSendDto{userId:X,sendStarus:2}
     * @return
     */
    @PostMapping("/selectSendOrderList")
    @ApiOperation(httpMethod = "POST", value = "分页获取所有记录")
    public Wrapper<List<OdsOrderDto>> list(@RequestBody DmsSendDto dmsSendDto) {
        if (dmsSendDto == null && dmsSendDto.getUserId() == null && dmsSendDto.getSendStatus() == null ){
            return WrapMapper.error("参数错误！");
        }
        if (dmsSendDto.getBeginTime() == null && dmsSendDto.getEndTime() == null ){
            dmsSendDto.setBeginTime(DateUtil.monthTimeBegin());
            dmsSendDto.setEndTime(DateUtil.nextMonthTimeBegin());
        }
        List<DmsSendDto> list = dmsSendService.selectSendOrderList(dmsSendDto);
        if (list == null || list.size() < 1){
            return WrapMapper.error("未查询到装车派送任务信息！");
        }
        List<Long> orderIds = list.stream().map(DmsSendDto::getOrderId).collect(Collectors.toList());
        List<OdsOrderDto> odsOrderDtoList = omcOrderFeignApi.getbyidS(orderIds);
        return WrapMapper.ok(odsOrderDtoList);
    }


    /**
     * 统计一个月，或者一段时间内司机送单数和送单金额、出勤天数
     * @param dmsSendDto
     * @return
     */
    @PostMapping("/sendOrderCount")
    @ApiOperation(httpMethod = "POST", value = "分页获取所有记录")
    public Wrapper<Map> sendOrderCount(@ApiParam(name = "dmsSend", value = "", defaultValue = "0")@RequestBody DmsSendDto dmsSendDto) {

        if (dmsSendDto == null && dmsSendDto.getUserId() == null && dmsSendDto.getSendStatus() == null ){
            return WrapMapper.error("参数错误！");
        }
        if (dmsSendDto.getBeginTime() == null && dmsSendDto.getEndTime() == null){
            //当月1号0点
            dmsSendDto.setBeginTime(monthTimeBegin());
            //当月月末23点59分59秒
            dmsSendDto.setEndTime(monthTimeEnd());
        }

        Byte employeeType = 2;
        Long groupId = 6L;
        Double driverNoCar = 0.0;
        Double driverWithCar = 0.0;
        Map map = new HashMap();
        map = dmsSendService.selectCountByCondition(dmsSendDto);

        //获得司机的类型
        AccEmployeeInfoDto accEmployeeInfoDto = new AccEmployeeInfoDto();
        accEmployeeInfoDto.setEmployeeDriver((byte)1);
        accEmployeeInfoDto.setUserId(dmsSendDto.getUserId());
        Wrapper listWrapper = uacUserFeignApi.selectEmployInfo(accEmployeeInfoDto);
        if (listWrapper.getCode() == 200 && listWrapper.getResult() != null ){
            List<UserInfoDto> userInfoDtos = (List<UserInfoDto>)listWrapper.getResult();
            if (userInfoDtos != null && userInfoDtos.size() > 0){
                employeeType = userInfoDtos.get(0).getEmployeeType();
                groupId = userInfoDtos.get(0).getGroupId();
            }
        }
        System.out.println("获得奖金标准"+groupId);
        //获得奖金标准
        CmsSysInfoDto cmsSysInfoDto = cmcFeignApi.getSysInfoDtoByType(groupId,18);
        if (cmsSysInfoDto != null && cmsSysInfoDto.getStatus() > 0) {
            JSONObject jsonObject = JSON.parseObject(cmsSysInfoDto.getInfoValue());
            driverNoCar = jsonObject.getDouble("driverNoCar");
            driverWithCar = jsonObject.getDouble("driverWithCar");
        }
        //根据司机类型，计算奖金
        System.out.println("根据司机类型，计算奖金="+map+"AAAA="+driverNoCar+"BBBB"+driverWithCar);
        Long salary = 0L;
        Long sumPay = 0L;
        map.put("salary",salary);

        if (map.get("sumPay") != null){
            sumPay = Long.parseLong(map.get("sumPay").toString());
        }

       if (employeeType.equals((byte)3)){
            salary = Math.round(sumPay * driverWithCar);
        }else{
            salary = Math.round(sumPay * driverNoCar);
        }

        map.put("salary",salary);


        //出勤天数
        map.put("countWorkDay",0);
        Map countMap = new HashMap();
        countMap.put("userId",dmsSendDto.getUserId());
        List<Map> mapList = uacUserFeignApi.countWorkDay(countMap);
        if (mapList != null && mapList.size() > 0){
            map.put("countWorkDay",mapList.get(0).get("total"));
        }
        System.out.println(map);
        return WrapMapper.ok(map);
    }

    /**
     * 统计一个月，或者一段时间内司机送单数和送单金额 的排名
     * @param dmsSendDto
     * @return
     */
    @PostMapping("/sendOrderCountByGroup")
    @ApiOperation(httpMethod = "POST", value = "分页获取所有记录")
    public Wrapper<List<Map>> sendOrderCountByGroup(@ApiParam(name = "dmsSend", value = "", defaultValue = "0")@RequestBody DmsSendDto dmsSendDto) {

        if (dmsSendDto == null && dmsSendDto.getUserId() == null && dmsSendDto.getSendStatus() == null ){
            return WrapMapper.error("参数错误！");
        }
        if (dmsSendDto.getBeginTime() == null && dmsSendDto.getEndTime() == null){
            //当月1号0点
            dmsSendDto.setBeginTime(monthTimeBegin());
            //当月月末23点59分59秒
            dmsSendDto.setEndTime(monthTimeEnd());
        }
        //sumPay,countSend
        List<Map> mapList = dmsSendService.sendOrderCountByGroup(dmsSendDto);

        AccEmployeeInfoDto accEmployeeInfoDto = new AccEmployeeInfoDto();
        //accEmployeeInfoDto.setEmployeeDriver((byte)1);
        Wrapper<List<UserInfoDto> > userInfoDtos = uacUserFeignApi.selectEmployInfo(accEmployeeInfoDto);
        if (mapList != null && userInfoDtos.getCode() == 200){
            List<UserInfoDto> userInfoDtoList = userInfoDtos.getResult();

            for(Map map : mapList){
                for(UserInfoDto item :userInfoDtoList){
                    if (map.get("userId").toString().equals(item.getUserId().toString())){
                        map.put("userName",item.getUserName());
                        map.put("headImgUri",item.getHeadImgUri());
                    }
                }
            }
        }

        return WrapMapper.ok(mapList);
    }
}
